package com.graduation.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation.common.exception.ManageException;
import com.graduation.common.result.R;
import com.graduation.common.utils.JwtHelper;
import com.graduation.common.utils.MD5;
import com.graduation.model.entity.Student;
import com.graduation.model.entity.Teacher;
import com.graduation.model.vo.SchoolInfoVo;
import com.graduation.model.vo.StudentQueryVo;
import com.graduation.user.constant.MapConstant;
import com.graduation.user.service.StudentService;
import com.graduation.user.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tianwenle
 * @since 2022-11-16
 */
@RestController
@RequestMapping("/admin/user/student")
public class StudentController {


    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/getCurrentUserInfo")
    public R getCurrentUserInfo(HttpServletRequest request) {

        String token = request.getHeader("X-Token");
        // 获取登录账号 查询用户的姓名
        String loginNo = JwtHelper.getLoginNo(token);

        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", loginNo);

        Student student = studentService.getOne(wrapper);

        if (student == null) {
            // 如果学生信息为空 那就判断是否为教师
            QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
            teacherQueryWrapper.eq("login_no", loginNo);
            Teacher teacher = teacherService.getOne(teacherQueryWrapper);
            if (teacher != null) {
                return R.ok().data("curUser", teacher);
            }
        } else {

            return R.ok().data("curUser", student);
        }
        return R.ok().data("name", "NULL");
    }


    // 根据学生登录用户名获取 学生的编号
    @GetMapping("/getStudentIdByUsername/{name}")
    public Long getStudentIdByUsername(@PathVariable("name") String name) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", name);
        Student student = studentService.getOne(wrapper);
        return student.getId();
    }

    @GetMapping("/getUsername")
    public R getUsername(HttpServletRequest request) {

        String token = request.getHeader("X-Token");
        // 获取登录账号 查询用户的姓名
        String loginNo = JwtHelper.getLoginNo(token);

        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", loginNo);

        Student student = studentService.getOne(wrapper);

        if (student == null) {
            // 如果学生信息为空 那就判断是否为教师
            QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
            teacherQueryWrapper.eq("login_no", loginNo);
            Teacher teacher = teacherService.getOne(teacherQueryWrapper);
            if (teacher != null) {
                return R.ok().data("name", teacher.getUsername());
            }
        } else {

            return R.ok().data("name", student.getUsername());
        }
        return R.ok().data("name", "NULL");
    }


    @PostMapping("/login")
    public R teacherLogin(@RequestBody Student student) throws UnsupportedEncodingException {
        String username = student.getUsername();
        String password = student.getPassword();

        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("login_no", username);

        wrapper.eq("password", MD5.encrypt(password));
        Student student1 = studentService.getOne(wrapper);

        if (student1 == null) {
            throw new ManageException("账号密码错误！");
        }

        // 登录成功 存储用户的名字
        MapConstant.MAP.put("user", student1.getUsername());

        redisTemplate.opsForValue().set("user", student1.getUsername());


        String token = JwtHelper.createToken(student1.getLoginNo(), student.getUsername(), "student");
        return R.ok().data("token", token);
    }

    /**
     * 编写info接口
     */
    @GetMapping("/info")
    public R infoShow(String token) throws UnsupportedEncodingException {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();

        wrapper.eq("login_no", JwtHelper.getLoginNo(token));
        Student student = studentService.getOne(wrapper);
        return R.ok().data("roles", Arrays.asList("admin")).data("introduction", "学生").data("avatar", student.getHeadUrl()).data("name", student.getNickName());
    }


    /*
        添加学生
     */
    @PostMapping("/add")
    public R addStudent(@RequestBody Student student) {
        // 这里读取到的数据需要重新赋值 stringMap存储的数据只能提供展示 不能使用
//        studentService.saveAndReload(student);
        // 出错原因 ： 存储的数据并没有添加进去，需要转换后再添加
//        studentService.save(student);

        studentService.addAndChangeInfo(student);

        return R.ok();
    }

    /*
        删除学生
     */
    @DeleteMapping("/delete/{id}")
    public R deleteStudent(@PathVariable("id") Long id) {
        studentService.removeById(id);
        return R.ok();
    }

    /**
     * 修改学生
     */
    @PutMapping("/update")
    public R updateStudent(@RequestBody Student student) {
//        studentService.updateById(student);
        studentService.saveAndReload(student);
        return R.ok();
    }

    /**
     * 查询学生信息
     */
    @GetMapping("/getById/{id}")
    public R getStudentById(@PathVariable("id") Long id) {
        Student student = studentService.getStudentById(id);
        return R.ok().data("student", student);
    }


    @GetMapping("/getFullStudentInfoById/{id}")
    public Student getFullStudentInfoById(@PathVariable("id") Long id){
        return studentService.getStudentById(id);
    }


    //
    @GetMapping("/getStudentById/{id}")
    public Student getStudent(@PathVariable("id") Long id) {
        Student student = studentService.getById(id);
        return student;
    }

    /**
     * 查询全部学生信息
     */
    @GetMapping("/list")
    public R getStudentList() {
        List<Student> list = studentService.getListInfo();
        return R.ok().data("list", list);
    }

    /**
     * 查询所有学生信息
     */
    @GetMapping("/getPackageStudentInfo")
    public R getPackageStudentInfo() {
        List<SchoolInfoVo> list = studentService.getPackageStudentInfo();
        return R.ok().data("list", list);
    }

    /**
     * 分页查询
     */
    @GetMapping("/page/{pageSize}/{pageNum}")
    public R pageList(@PathVariable Integer pageSize, @PathVariable Integer pageNum, StudentQueryVo studentQueryVo) {
        Map<String, Object> map = studentService.findPageList(pageSize, pageNum, studentQueryVo);
        return R.ok().data(map);
    }

    /**
     * 获取当前老师下面的所有学生
     */
    @GetMapping("/getStudentTeacherList")
    public R getStudentByTeacherUserName(HttpServletRequest request) throws UnsupportedEncodingException {

        String token = request.getHeader("X-Token");

        String loginNo = JwtHelper.getLoginNo(token);

        if (loginNo == null) {
            throw new ManageException("登录失效，请重新登录！");
        }
        List<SchoolInfoVo> list = studentService.getTeacherStudentList(loginNo);
        return R.ok().data("list", list);
    }


    /**
     * 查询当前老师的所有学生
     */
    @GetMapping("/getMyStudent/{pageSize}/{pageNum}")
    public R getMyStudent(@PathVariable Integer pageSize, @PathVariable Integer pageNum, StudentQueryVo studentQueryVo, HttpServletRequest request) throws UnsupportedEncodingException {

        String token = request.getHeader("X-Token");

        String loginNo = JwtHelper.getLoginNo(token);

        if (loginNo == null) {
            throw new ManageException("登录失效，请重新登录！");
        }

        Map<String, Object> map = studentService.pageMyStudent(pageNum, pageSize, studentQueryVo, loginNo);

        return R.ok().data(map);
    }

    /**
     * 获取当前用户身份信息
     */

    @GetMapping("/getStudentByUsername")
    public R getStudentByUsername(HttpServletRequest request) throws UnsupportedEncodingException {
        String token = request.getHeader("X-Token");

        String loginNo = JwtHelper.getLoginNo(token);

        if (loginNo == null) {
            throw new ManageException("登录失效，请重新登录！");
        }

        Student student = studentService.getStudentInfoDetail(loginNo);

        return R.ok().data("student", student);
    }

}

